package com.ruicar.afs.cloud.admin.config;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.exception.NacosException;
import com.ruicar.afs.cloud.admin.properties.RouterDefineProperties;
import com.ruicar.afs.cloud.admin.service.SysRouteConfService;
import com.ruicar.afs.cloud.common.core.nacos.NacosHelper;
import com.ruicar.afs.cloud.common.core.security.service.AfsNoPassLoginService;
import com.ruicar.afs.cloud.common.core.security.service.DefaultAfsNoPassLoginService;
import com.ruicar.afs.cloud.common.gateway.support.DynamicRouteInitEvent;
import com.ruicar.afs.cloud.common.gateway.vo.RouteDefinitionVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.config.PropertiesRouteDefinitionLocator;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;

import java.net.URI;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * @author Fzero
 * @date 2019-01-24
 * <p>
 * 容器启动后保存配置文件里面的路由信息到 nacos
 */
@Slf4j
@Configuration
@AllArgsConstructor
@Import(RouterDefineProperties.class)
public class DynamicRouteInitRunner {

	private final NacosHelper nacosHelper;
	private final SysRouteConfService routeConfService;

	private final RouterDefineProperties routerDefineProperties;

	private final StringRedisTemplate stringRedisTemplate;

	@Async
	@Order
	@EventListener({WebServerInitializedEvent.class, DynamicRouteInitEvent.class})
	public void initRoute() {
		List<RouteDefinitionVo> list = routeConfService.routes().stream().map(route->{
			RouteDefinitionVo vo = new RouteDefinitionVo();
			vo.setRouteName(route.getRouteName());
			vo.setId(route.getRouteId());
			vo.setUri(URI.create(route.getUri()));
			vo.setOrder(route.getOrder());
			JSONArray predicateObj = JSONUtil.parseArray(route.getPredicates());
			vo.setPredicates(predicateObj.toList(PredicateDefinition.class));
			log.info("加载路由ID：{},{}", route.getRouteId(), vo);
			return vo;
		}).collect(toList());
		try {
			nacosHelper.getConfigServer()
					.publishConfig(routerDefineProperties.getDataId(), routerDefineProperties.getGroupName(), JSON.toJSONString(list));
			log.debug("初始化网关路由结束 ");
		}catch (NacosException e){
			log.error("初始化网关路由失败",e);
		}
	}

	/**
	 * 配置文件设置为空nacos 加载的为准
	 *
	 * @return
	 */
	@Bean
	public PropertiesRouteDefinitionLocator propertiesRouteDefinitionLocator() {
		return new PropertiesRouteDefinitionLocator(new GatewayProperties());
	}
}
